package com.hs.srm.admin.modules.requisition.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.hs.srm.admin.modules.inforecord.service.InforecordService;
import com.hs.srm.admin.modules.pricemanagement.service.*;
import com.hs.srm.admin.modules.pricemanagement.vo.EssentialInformationVO;
import com.hs.srm.admin.modules.quota.service.QuotaService;
import com.hs.srm.admin.modules.requisition.entity.NproPurchRequestItemEntity;
import com.hs.srm.admin.modules.requisition.entity.ProPurchRequestItemEntity;
import com.hs.srm.admin.modules.requisition.service.ProPurchRequestHeaderService;
import com.hs.srm.admin.modules.requisition.service.ProPurchRequestItemService;
import com.hs.srm.admin.modules.requisition.service.SupplyGoodsService;
import com.hs.srm.admin.modules.ssess.service.SsessService;
import com.hs.srm.admin.modules.sys.controller.AbstractController;
import com.hs.srm.admin.modules.vendor.service.VendorService;
import com.hs.srm.base.common.annotation.SysLog;
import com.hs.srm.base.common.utils.EntityUtils;
import com.hs.srm.base.modules.sys.entity.SysRoleEntity;
import com.hs.srm.base.modules.sys.entity.SysUserEntity;
import com.hs.srm.base.modules.sys.service.SysRoleService;
import com.hs.srm.base.modules.sys.service.SysUserService;
import com.hs.srm.common.utils.PageUtils;
import com.hs.srm.common.utils.R;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;


/**
 * @author yanfei
 * @date 2019年2月14日
 * 生产性采购申请行项目
 */
@RestController
@RequestMapping("/proPurchRequestItem")
public class ProPurchRequestItemController extends AbstractController {

    private static final long serialVersionUID = -4123823577744890422L;
    // 注入业务层
    @Autowired
    private ProPurchRequestItemService proPurchRequestItemService;
    @Autowired
    private ProPurchRequestHeaderService proPurchRequestHeaderService;

    @Autowired
    private EssentialInformationService essentialInformationServiceImpl;

    @Autowired
    private InforecordService inforecordService;


    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        params.put("purch_request_type", "zbz");
        PageUtils page = this.proPurchRequestItemService.queryPage(params);
        List<ProPurchRequestItemEntity> list = (List<ProPurchRequestItemEntity>) page.getList();
        list = EntityUtils.valToTxt(list);
        page.setList(list);
        return R.ok(page);
    }


    /**
     * 货源分配
     *
     * @param
     * @return
     */
    @RequestMapping("/toEdit/{pkId}")
    public ModelAndView toEdit(@PathVariable("pkId") String pkId) {
        //通过Id查询抬头信息
        ProPurchRequestItemEntity proPurchRequestItemEntity = this.proPurchRequestItemService.selectById(pkId);
        //采购申请单号
        String purchRequestCode = proPurchRequestItemEntity.getPurchRequestCode();
        List<ProPurchRequestItemEntity> itemlist = this.proPurchRequestItemService.findByNo(purchRequestCode, null);
        //把查询出来的对象赋值给供应商实体
        ModelAndView modelAndView = new ModelAndView("modules/requisition/prorequisition_edit");
        modelAndView.addObject("proPurchRequestItemEntity", proPurchRequestItemEntity);
        modelAndView.addObject("itemlist", itemlist);
        return modelAndView;
    }

    @RequestMapping(value = "/toAllot")
    public void toAllot(@RequestParam(value = "materialCode") String materialCode, @RequestParam(value = "factory") String factory
            , @RequestParam(value = "pkId") String pkId, HttpServletRequest request, HttpServletResponse response) {
        List<EssentialInformationVO> itemlist = new ArrayList<>();
        String strpath = "/proPurchRequestItem/Jump";
        //ProPurchRequestItemEntity proPurchRequestItemEntity=this.proPurchRequestItemService.selectById(pkId);
        //根据物料号和工厂匹配信息记录维护
        List<EssentialInformationVO> listItem = this.essentialInformationServiceImpl.findByNos(factory, materialCode, pkId);
        //是否从配额取数据，配额：true，信息记录：false
        boolean isFromQuota = false;
        //配额取值，判断时间是否超时间段
        boolean isOverTime = false;
        //配额总量
        int quotaCount = 0;
        //申请量
        int applyCount = 0;
        for (EssentialInformationVO essentialInformationVO : listItem) {
            applyCount = essentialInformationVO.getApplyQty().intValue();
            //剩余配额量
            BigDecimal restQuotaNum = essentialInformationVO.getQuotaNum().subtract(essentialInformationVO.getUsedQuotaNum());
            //配额数不为空、不为0
            if (restQuotaNum != null && !"".equals(restQuotaNum) && restQuotaNum.compareTo(new BigDecimal(0)) != 0) {
                quotaCount += restQuotaNum.intValue();
                //配额取值，判断时间是否超时间段
                String startDate = essentialInformationVO.getStartDate();
                String endDate = essentialInformationVO.getEndDate();
                //当前日期
                String now = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.CHINA).format(LocalDate.now());
                //当前日期在配额有效日期内则从配额取值
                if (StringUtils.isBlank(startDate) || now.compareTo(startDate) < 0 || now.compareTo(endDate) > 0) {
                    isOverTime = true;
                } else {
                    essentialInformationVO.setPkId(pkId);//联合主键 供应商编码+工厂+物料号
                    essentialInformationVO.setQuotaNum(essentialInformationVO.getQuotaNum());
                    itemlist.add(essentialInformationVO);
                    isFromQuota = true;
                }
            }
        }
        if (quotaCount != 0 && quotaCount < applyCount) {
            strpath = "/proPurchRequestItem/err";
            request.setAttribute("message", "总配额数量小于申请数量(" + applyCount + ")");
        } else if (isOverTime) {
            strpath = "/proPurchRequestItem/err";
            request.setAttribute("message", "当前日期不在配额规定时间段内！");
        } else if (quotaCount == 0) {//从信息记录取
            listItem.clear();
            itemlist.clear();
            //从信息记录取数据
            listItem = this.essentialInformationServiceImpl.simplfindByNos(factory, materialCode, pkId);
            for (EssentialInformationVO essentialInformationVO : listItem) {
                essentialInformationVO.setPkId(pkId);//联合主键 供应商编码+工厂+物料号
                essentialInformationVO.setQuotaNum(essentialInformationVO.getQuotaNum());
                isFromQuota = false;
                itemlist.add(essentialInformationVO);
            }
        }

        itemlist.forEach(item -> {
            //sap中价格只能两位小数，价格增大十倍则价格单位也增大十倍，价格/价格单位 = 真实价格
            item.setPrice(item.getPrice().divide(new BigDecimal(item.getPriceUnit())));
            item.setPriceUnit("1");
            //库存地点_工厂，拼接成数据字典中格式
            item.setStorageLocation(item.getStorageLocation() + "_" + item.getFactory());
        });
        RequestDispatcher rd = request.getRequestDispatcher(strpath);
        request.setAttribute("itemList", itemlist);
        request.setAttribute("isFromQuota", isFromQuota);
        try {
            rd.forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @RequestMapping(value = "/orderFromSG")
    public void orderFromSG(@RequestParam(value = "sgId") String sgId, @RequestParam(value = "itemId") String itemId,
                            HttpServletRequest request, HttpServletResponse response) {
        EssentialInformationVO item;
        List<EssentialInformationVO> itemlist = new ArrayList<>();
        String strpath = "/proPurchRequestItem/Jump";
        //根据供应商编码和itemID查找数据
        item = this.essentialInformationServiceImpl.findByCodeItemId(sgId, itemId);
        item.setPkId(itemId);
        //库存地点_工厂，拼接成数据字典中格式
        item.setStorageLocation(item.getStorageLocation() + "_" + item.getFactory());
        itemlist.add(item);
        //是否从配额取数据，配额：true，信息记录：false
        boolean isFromQuota = false;
        RequestDispatcher rd = request.getRequestDispatcher(strpath);
        request.setAttribute("itemList", itemlist);
        request.setAttribute("isFromQuota", isFromQuota);
        try {
            rd.forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 货源分配跳转页面
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/Jump", method = RequestMethod.GET)
    public ModelAndView Jump(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView modelAndView = new ModelAndView("modules/requisition/prorequisition_edit");
        modelAndView.addObject("itemList", request.getAttribute("itemList"));
        modelAndView.addObject("isFromQuota", request.getAttribute("isFromQuota"));
        return modelAndView;
    }

    /**
     * 批量提交
     */
    @SysLog("批量提交")
    @RequestMapping("/insertBatch")
    //@RequiresPermissions("inquiryHeader:insertBatch")
    public R insertBatch(@RequestBody String param) {
        // 创建一个JSONObject对象，返回数据ResponseBody用
        JSONObject jsonObject = JSONObject.parseObject(param);
        //json字符数据转成
        List<String> list = JSONArray.parseArray(jsonObject.getString("pkid"), String.class);
        //根据询价单id查询对应行项目
        List<ProPurchRequestItemEntity> proPurchRequestItemlist = this.proPurchRequestItemService.selectBatchIds(list);
        for (ProPurchRequestItemEntity proPurchRequestItem : proPurchRequestItemlist) {
            if (proPurchRequestItem.getGoodsStatus() == -2) {
                proPurchRequestItem.setGoodsStatus(-1);
                this.proPurchRequestItemService.updateById(proPurchRequestItem);
            }
            return R.ok().put("result", "err");
        }
        return R.ok().put("result", "ok");
    }


    /**
     * 询价
     *
     * @param
     * @return
     */
    @RequestMapping("/inquiry/{pkId}")
    public ModelAndView inquiry(@PathVariable("pkId") String pkId) {
        //通过Id查询抬头信息
        ProPurchRequestItemEntity proPurchRequestItemEntity = this.proPurchRequestItemService.selectById(pkId);
        //采购申请单号
        String purchRequestCode = proPurchRequestItemEntity.getPurchRequestCode();
        List<ProPurchRequestItemEntity> itemlist = this.proPurchRequestItemService.findByNo(purchRequestCode, null);
        //把查询出来的对象赋值给供应商实体
        ModelAndView modelAndView = new ModelAndView("modules/requisition/prorequisition_edit");
        modelAndView.addObject("proPurchRequestItemEntity", proPurchRequestItemEntity);
        modelAndView.addObject("itemlist", itemlist);
        return modelAndView;
    }

    /**
     * 错误信息
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/err", method = RequestMethod.GET)
    public ModelAndView err(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView modelAndView = new ModelAndView("modules/error/data_101");
        modelAndView.addObject("message", request.getAttribute("message"));
        return modelAndView;
    }

    /**
     * 根据物料号、工厂判断信息记录中是否有该条记录
     *
     * @param materialCode 物料号
     * @return true/false
     */
    @RequestMapping("/checkRecord")
    public R checkRecord(@RequestParam(value = "materialCode") String materialCode) {
        boolean result = inforecordService.checkRecord(materialCode);
        return R.ok(result);
    }

    /**
     * 根据物料号、工厂判断货源记录中是否有该条记录
     *
     * @param materialCode 物料号
     * @return true/false
     */
    @RequestMapping("/checkRecordFromSupplyGoods")
    public R checkRecordFromSupplyGoods(@RequestParam(value = "materialCode") String materialCode, @RequestParam(value = "factory") String factory) {
        boolean result = inforecordService.checkRecordFromSupplyGoods(materialCode, factory);
        return R.ok(result);
    }

    /**
     * 订单驳回后可修改为草稿状态
     */
    @RequestMapping("/changeStatus")
    public R changeStatus(@RequestParam(value = "pkIds[]") String[] pkIds) {
        List<ProPurchRequestItemEntity> proPurchRequestItemlist = proPurchRequestItemService.selectBatchIds(Arrays.asList(pkIds));
        proPurchRequestItemlist.forEach(item -> item.setGoodsStatus(ProPurchRequestItemEntity.CAOGAO));
        boolean b = proPurchRequestItemService.updateBatchById(proPurchRequestItemlist);
        if (!b) {
            return R.error();
        }
        return R.ok();
    }

    @RequestMapping("/findById")
    public R findbypkId(@RequestParam(value = "pkId[]") String[] pkId) {
        String str = pkId[0];
        ProPurchRequestItemEntity ProPurchRequestItemEntity = this.proPurchRequestItemService.findbypkId(str);
        return R.ok(ProPurchRequestItemEntity);
    }

    /**
     * 修改所有
     */
    @SysLog("生产性请购单修改")
    @RequestMapping("/updateAll")
    public R updateAll(String data, String pkId) {
        ProPurchRequestItemEntity ProPurchRequestItemEntity = JSONObject.parseObject(data, ProPurchRequestItemEntity.class);
        ProPurchRequestItemEntity.setPkId(pkId);
        ProPurchRequestItemEntity.setGoodsStatus(-2);
        this.proPurchRequestItemService.updateAll(ProPurchRequestItemEntity);
        return R.msg("更新成功!");
    }

    /**
     * @Description 获取采购组抬头信息
     * @Param [purchGroup] 采购组
     * @Return com.hs.srm.common.utils.R 返回数据
     */
    @RequestMapping("/getCount")
    public R getCount() {
        String username = this.getUser().getUsername();
        int[] nums = new int[4];
        //所有申请单
        nums[0] = this.proPurchRequestItemService.selectCount(new EntityWrapper<ProPurchRequestItemEntity>().eq("purch_group", username).eq("delete_flag", 0));
        //查未完成
        nums[1] = this.proPurchRequestItemService.selectCount(new EntityWrapper<ProPurchRequestItemEntity>().eq("purch_group", username).eq("goods_status", NproPurchRequestItemEntity.CAOGAO).eq("delete_flag", 0));
        //查询询价
        nums[2] = this.proPurchRequestItemService.selectCount(new EntityWrapper<ProPurchRequestItemEntity>().eq("purch_group", username).notIn("goods_status", -2, 0).eq("delete_flag", 0));
        //查询完成
        nums[3] = this.proPurchRequestItemService.selectCount(new EntityWrapper<ProPurchRequestItemEntity>().eq("purch_group", username).eq("goods_status", 0).eq("delete_flag", 0));
        return R.ok(nums);
    }

    /**
     * 根据pkId批量逻辑删除申请单
     *
     * @param pkIds 要删除的申请单id
     * @return
     */
    @SysLog("删除生产性请购单")
    @RequestMapping("/deleteRequisition")
    public R deleteRequisition(@RequestParam(value = "pkId[]") String[] pkIds) {
        List<ProPurchRequestItemEntity> itemEntityList = proPurchRequestItemService.selectBatchIds(Arrays.asList(pkIds));
        itemEntityList.forEach(item -> item.setDeleteFlag("1"));
        boolean msg = proPurchRequestItemService.updateBatchById(itemEntityList);
        if (msg) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 生产性申请单生成多个行项目订单
     *
     * @param pkIds
     * @return
     */
    @SysLog("生产性生成订单")
    @PostMapping("/proCreateOrder")
    public R proCreateOrder(@RequestParam(value = "pkIds[]") String[] pkIds, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<ProPurchRequestItemEntity> itemEntityList = proPurchRequestItemService.selectBatchIds(Arrays.asList(pkIds));

        //将数据封装成分配货源时的json数据，调用以前生成订单的接口
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("isFromQuota", "false");
        JSONArray jsonArray = new JSONArray();
        jsonObject.put("essentialInformationVO", jsonArray);
        itemEntityList.forEach(item -> {
            JSONObject data = new JSONObject();
            data.put("essentialInformationVO", JSONObject.parseObject(item.getDistributeData()));
            jsonArray.add(data);
        });
        //生成订单
        return proPurchRequestHeaderService.updateSource(jsonObject, this.getUser().getUsername());
    }
}

